package tech.aistar.prj.service.impl;

import org.apache.ibatis.session.SqlSession;
import tech.aistar.prj.mapper.UserMapper;
import tech.aistar.prj.model.pojo.User;
import tech.aistar.prj.service.IUserService;

import tech.aistar.prj.util.MybatisUtil;

import java.sql.SQLException;
import java.util.List;

/**
 * 本类用来演示: service层 - 处理数据的 - 负责业务的处理
 *
 * service层调用mapper层[crud操作,不负责业务逻辑的]
 *
 * @author: success
 * @date: 2022/3/22 8:46 上午
 */
public class UserServiceImpl implements IUserService {
    @Override
    public User login(String username) {
        SqlSession sqlSession = null;
        UserMapper userMapper = null;
        User user = null;
        try {
            sqlSession = MybatisUtil.getSession();
            userMapper = sqlSession.getMapper(UserMapper.class);
            //可以进行参数的校验,统计,分析等....
            user = userMapper.findByUserName(username);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            MybatisUtil.close(sqlSession);
        }
        return user;
    }

    @Override
    public List<User> findAll() {
        List<User> users = null;
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            users = userMapper.findAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            MybatisUtil.close(sqlSession);
        }
        return users;
    }
    @Override
    public User getById(Integer id) {
        User user = null;
        SqlSession sqlSession = null;
        try {
            sqlSession = MybatisUtil.getSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            user = userMapper.findById(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            MybatisUtil.close(sqlSession);
        }
        return user;
    }
}
